from flask import render_template, request, redirect, url_for, flash, Blueprint
from models import Category, Suggestion, AccessLog
from extensions import db
from datetime import datetime, timedelta, timezone
import re
import ipaddress
from utils.AutoEmail import AutoEmail
from utils.ip_region import get_ip_region

frontend_bp = Blueprint('frontend', __name__)


def is_valid_email(email):
    return re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email)


def get_ip_info():
    ip = request.headers.get('X-Forwarded-For', request.remote_addr)
    try:
        is_internal = ipaddress.ip_address(ip).is_private
        return ip, None if is_internal else ip
    except Exception as e:
        return ip, None


def record_access_once(path: str, per: str = 'day'):
    """
    通用访问日志记录器
    :param path: 访问路径
    :param per: 'day' 或 'hour' 控制频率
    """
    ip, original_ip = get_ip_info()
    print(ip, original_ip)
    now = datetime.now(timezone.utc)
    if per == 'day':
        cutoff = datetime(now.year, now.month, now.day)
    elif per == 'hour':
        cutoff = now - timedelta(hours=1)
    else:
        cutoff = now

    exists = AccessLog.query.filter(
        AccessLog.ip == ip,
        AccessLog.path == path,
        AccessLog.created_at >= cutoff
    ).first()

    if not exists:
        country, province, city, source = '', '', '', ''
        if original_ip:
            region_str, country, province, city = get_ip_region(original_ip)
            source = region_str or ''
        log = AccessLog(
            ip=ip,
            original_ip=original_ip,
            path=path,
            source=source,
            country=country,
            province=province,
            city=city
        )
        db.session.add(log)
        db.session.commit()


@frontend_bp.route('/', methods=['GET'])
def index():
    record_access_once(path='/', per='day')
    return render_template('/index.html', categories=Category.query.all())


@frontend_bp.route('/suggest', methods=['GET', 'POST'])
def suggest():
    categories = Category.query.all()
    if request.method == 'POST':
        ip, _ = get_ip_info()
        email = request.form.get('email', '').strip()
        site_name = request.form.get('site_name', '').strip()
        site_url = request.form.get('site_url', '').strip()
        site_description = request.form.get('site_description', '').strip()
        site_logo = request.form.get('site_logo', '').strip()
        category_id = request.form.get('category_id')
        print(email, site_name, site_url, site_description, site_logo, category_id)
        # 校验基本字段
        if not site_name or not site_url or not site_description or not category_id:
            flash('请填写完整的推荐信息（姓名、网站名、链接、描述、分类）')
            return redirect(url_for('frontend.suggest'))

        # 校验邮箱
        if email and not is_valid_email(email):
            flash('无效的邮箱地址')
            return redirect(url_for('frontend.suggest'))

        # 校验分类是否存在
        category = Category.query.get(category_id)
        if not category:
            flash('所选分类无效')
            return redirect(url_for('frontend.suggest'))

        suggestion = Suggestion(
            ip=ip,
            email=email,
            site_name=site_name,
            site_url=site_url,
            site_description=site_description,
            site_logo=site_logo,
            category_id=category.id
        )

        db.session.add(suggestion)
        db.session.commit()

        flash('感谢您的推荐，我们会尽快审核！')
        return redirect(url_for('frontend.suggest'))

    record_access_once(path='/suggest', per='hour')
    return render_template('/suggest.html', categories=categories)
